package com.atguigu.crowd.handler;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.po.MemberPO;
import com.atguigu.crowd.service.api.MemberService;
import com.atguigu.crowd.util.ResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class MemberProviderHandler {

    @Autowired
    private MemberService memberService;


    Logger logger = LoggerFactory.getLogger(MemberProviderHandler.class);


    @RequestMapping("/save/member/remote")
    public ResultEntity<MemberPO> saveMember(@RequestBody MemberPO memberPO) {

        try{
            logger.info("开始保存表单信息");
            //保存数据至数据库，并返回一个成功的消息
            memberService.saveMember(memberPO);
            logger.info("保存成功");
            return ResultEntity.successWithoutData();
        }catch (Exception e) {

            //如果异常类型为DuplicateKeyException
            if (e instanceof DuplicateKeyException) {
                return ResultEntity.failed(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
            //如果抛出的异常为其它异常
            return ResultEntity.failed(e.getMessage());
        }
    }



    @RequestMapping("/get/memberpo/by/login/acct/remote")
    public ResultEntity<MemberPO> getMemberPOByLoginAcctRemote (@RequestParam("loginacct") String loginacct) {
        try {
            //调用本地的service执行数据库查询
            MemberPO memberPo = memberService.getMemberPOByLoginAcct(loginacct);
            //如果没有抛异常就返回结果
            return ResultEntity.successWithData(memberPo);
        }catch (Exception e) {
            //捕获异常
            e.printStackTrace();
            //返回异常信息
            return ResultEntity.failed(e.getMessage());
        }
    }




}
